﻿using Abp.AspNetCore.Mvc.Authorization;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Mt.Site.Application.SEO;
using Mt.Site.Application.SEO.Dto;
using Mt.Site.Core.Base.Domain.Entities.ShortId;
using Mt.Site.Core.Base.Utils.Excel.Import;
using Mt.Site.Core.ContentManagement.Entities;
using Mt.Site.Core.Navigations.Entities;
using Mt.Site.Core.Navigations.Route;
using Mt.Site.Core.SEO;
using Mt.Site.Core.Url;
using Mt.Site.Web.Areas.B.Models.SEO;
using Mt.Site.Web.Controllers;
using System;
using System.Threading.Tasks;
using System.Transactions;

namespace Mt.Site.Web.Areas.B.Controllers
{
    [Area("B")]
    public class SeoController : MtSiteControllerBase
    {
        private readonly ISeoAppService _seoAppService;

        private readonly IRouteDataChecker _routeDataChecker;

        private readonly IShortIdManager _shortIdManager;

        private readonly IRepository<ContentBase, Guid> _contentRepository;

        private readonly IRepository<Menu, Guid> _menuRepository;

        private readonly IRouteChecker _routeChecker;

        public SeoController(
            ISeoAppService seoAppService,
            IRouteChecker routeChecker,
            IRouteDataChecker routeDataChecker,
            IShortIdManager shortIdManager,
            IRepository<ContentBase, Guid> contentRepository,
            IRepository<Menu, Guid> menuRepository)
        {
            _seoAppService = seoAppService;
            _routeDataChecker = routeDataChecker;
            _shortIdManager = shortIdManager;
            _contentRepository = contentRepository;
            _menuRepository = menuRepository;
            _routeChecker = routeChecker;
        }

        [HttpPost]
        [AbpMvcAuthorize(SeoPermissions.Pages_Manange_Tenant_Seo)]
        public async Task<ActionResult> ImportSeoDataAsync()
        {
            // 调整 GetRelateID方法
            throw new NotImplementedException();

            var helper = new SeoListExcelDataReader();

            try
            {
                var result = new ExcelImport<ImportSeoDto>(helper).Inport(HttpContext.Request, "file", 20, 1);
                foreach (var item in helper.Data)
                {
                    if(item.CanBeImported())
                    {
                        if (item.Url.IsNullOrEmpty())
                        {
                            continue;
                        }

                        Guid? relateId = await GetRelateID(item);

                        if (relateId == null)
                        {
                            helper.Rejects.Add(item.Url);
                            continue;
                        }

                        using (var uow = UnitOfWorkManager.Begin(new UnitOfWorkOptions
                        {
                            Scope = TransactionScopeOption.RequiresNew
                        }))
                        {
                            await _seoAppService.CreateOrUpdateSeoSetting(new CreateOrUpdateSeoInput
                            {
                                RelatedId = relateId.Value,
                                KeyWords = item.Keywords,
                                Title = item.Title,
                                Description = item.Description
                            });
                            await uow.CompleteAsync();
                        }
                    }
                    else
                    {
                        if (!item.Url.IsNullOrEmpty())
                        {
                            helper.Rejects.Add(item.Url);
                        }
                    }
                }

                string msg = $"({helper.Rejects.Count})条数据导入失败:\n{string.Join(",\n", helper.Rejects)}";
                return Json(new { msg = msg });
            }
            catch (Exception ex)
            {
                return Json(new AjaxResponse(new ErrorInfo("Upload error :" + ex.Message)));
            }
        }

        private async Task<Guid?> GetRelateID(ImportSeoDto item)
        {
            Guid? relateId = null;

            Uri uri = new Uri(item.Url);
            var absolutePath = uri.AbsolutePath;//不带域名，不带参数，‘/’开头
            if (absolutePath != "/")
            {
                absolutePath = $"/cn/zh-cn{absolutePath}";
                var url = _routeChecker.DiyUrlToRealUrl(absolutePath, out bool _);

                var data = await _routeDataChecker.GetRouteDataByUrlAsync(url);
                object value, value2;
                int id = 0, kind = 0;
                if (data.Values.TryGetValue("id", out value) && value != null)
                {
                    int.TryParse(value.ToString(), out id);
                }
                if (data.Values.TryGetValue("kind", out value2) && value2 != null)
                {
                    int.TryParse(value2.ToString(), out kind);
                }

                if (id > 0)
                {
                    var id2 = await _shortIdManager.GetAuxiliaryIdAsync(id);
                    relateId = (await _contentRepository.FirstOrDefaultAsync(t => t.AuxiliaryId == id2))?.Id;
                }
                else if (kind > 0)
                {
                    var kind2 = await _shortIdManager.GetAuxiliaryIdAsync(kind);
                    relateId = (await _menuRepository.FirstOrDefaultAsync(t => t.AuxiliaryId == kind2))?.Id;
                }
            }
            else
            {
                relateId = Guid.Parse("dcf907d1-296c-449e-b7cb-4cdcb2ee9541");
            }

            return relateId;
        }
    }
}
